<template>
	<div v-show="!noData" ref="echartsRef" class="chart-box"></div>
	<el-empty v-show="noData" description="暂无数据" :image-size="80" class="chart-box"></el-empty>
</template>

<script setup lang="ts" name="lineChart">
import { onMounted, ref, watch, nextTick } from 'vue';
import * as echarts from 'echarts';
import { useEcharts } from '/@/hooks/useEcharts';
import { fenToYuan, scale2Format } from '/@/utils/commonFunction';
const echartsRef = ref<HTMLElement>();

interface Props {
	option: any;
}

// // 默认值
let props = withDefaults(defineProps<Props>(), {
	option: { data: [], xData: [] },
});

const noData = ref(true);

const initChart = (options: any) => {
	let total = options.data.reduce((pre: number, cur: any) => pre + cur.value, 0);
	if (total == 0) return;
	noData.value = false;
	nextTick(() => {
		let myChart: echarts.ECharts = echarts.init(echartsRef.value as HTMLElement);
		let option: echarts.EChartsOption = {
			tooltip: {
				trigger: 'item',
				formatter: (params: any) => {
					return options.tooltipFormatter
						? options.tooltipFormatter(params)
						: `<div>
					${params.marker} ${params.name}<br/>
					<div class='font13 mt5' style='line-height: 24px'>
						支付金额：${fenToYuan(params.value)}元 <br/>
						金额占比：${scale2Format(params.data.proportion)}%
					</div>
				</div>`;
				},
			},
			legend: {
				orient: 'vertical',
				top: 'center',
				right: '20',
				icon: 'pin',
				formatter: (name) => {
					const target = options.data.find((v: any) => v.name == name);
					target.proportion = (target.value / total) * 100 + '';
					return options.legendFormatter
						? options.legendFormatter(target)
						: `${target.name} ${fenToYuan(target.value)}元 ${scale2Format(target.proportion)}%`;
				},
			},
			series: [
				{
					name: 'Access From',
					type: 'pie',
					radius: ['40%', '60%'],
					center: ['25%', '50%'],
					avoidLabelOverlap: false,
					label: {
						show: false,
						position: 'center',
					},
					emphasis: {
						label: {
							show: true,
							fontSize: 20,
							fontWeight: 'bold',
						},
					},
					labelLine: {
						show: false,
					},
					data: options.data,
				},
			],
		};
		// if (options.legend) {
		// 	option['legend'] = {
		// 		left: 20,
		// 		top: 0,
		// 		data: options.legend,
		// 		textStyle: {
		// 			color: '#a1a1a1',
		// 		},
		// 	};
		// }
		useEcharts(myChart, option);
	});
};

watch(
	() => props.option,
	(val) => {
		initChart(val);
	},
	{
		deep: true,
	}
);

onMounted(() => {
	initChart(props.option);
});
</script>

<style scoped lang="scss">
@import './chart.scss';
</style>
